﻿using ConfExpert.Utility;
using DevExpress.XtraEditors.Repository;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace ConfExpert.Forms.ImportWizards
{
    public partial class SiparisAktar : XImportWizard
    {
        int CustomerId;
        public SiparisAktar(int CustomerId)
        {
            InitializeComponent();
            this.CustomerId = CustomerId;

            DataTable dtM = AppSession.Lookups.Brand.Select("CustomerId = " + CustomerId.ToStr()).CopyToDataTable();
            RepositoryItemGridLookUpEdit riBrand = GetCustomGLE(dtM, "Name", "BrandId");
            gleMarka.Edit.Assign(riBrand);

            if (dtM.Rows.Count == 1)
                gleMarka.EditValue = dtM.Rows[0]["BrandId"];

            gleTalepTipi.EditValue = 1;

            gleSezon.Edit.Assign(RI(Rp.Sezon));
            gleDagilim.Edit.Assign(RI(Rp.Dagilim));
            gleTalepTipi.Edit.Assign(RI(Rp.TalepTipi));

            Init("SiparisAktar", false);
            this.FileDone += SiparisAktar_FileDone;
            this.ProcessDone += SiparisAktar_ProcessDone;
            this.ProcessStart += SiparisAktar_ProcessStart;

            btnSave.Enabled = btnProcessFile.Enabled = false;
            btnSave.ItemClick += BtnSave_ItemClick;
            splitter.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
            gleDagilim.EditValueChanged += gleDagilim_EditValueChanged;
            dtDagilim = ExecuteDataTable("GetDagilimVertical2");
        }

        int DagilimId = 0;
        void gleDagilim_EditValueChanged(object sender, EventArgs e)
        {
            DagilimId = gleDagilim.EditValue.ToInt();
            btnProcessFile.Enabled = DagilimId > 0;
            if (DagilimId > 0)
            {
                dag = new Dictionary<string, string>();
                foreach (DataRow r in dtDagilim.Select("DagilimId=" + DagilimId.ToStr()))
                    dag[r["Beden"].ToStr()] = r["Name"].ToStr();
            }
        }

        string Adet, Beden;
        Dictionary<string, string> dag;
        Dictionary<string, cx> cols;
        List<string> zorunlu;
        DataTable dtOrd, dtDagilim;
        void SiparisAktar_ProcessStart()
        {
            DataTable ordine = ExecuteDataTable("GetOrdine_Template", CustomerId);

            cols = new Dictionary<string, cx>();
            zorunlu = new List<string>();
            dtOrd = new DataTable();
            dtOrd.Columns.Add("idx", typeof(int));

            dtOrd.SetPK("idx");
            dtOrd.AddAutoIncrementalColumn("idx");

            dtOrd.Columns.Add("DosyaAdi", typeof(string));
            foreach (DataRow r in ordine.Rows)
            {
                dtOrd.Columns.Add(r["Col"].ToStr(), Type.GetType(r["DataType"].ToStr()));

                cx x = new cx();
                x.Col = r["Col"].ToString();
                x.CaptionTR = r["CaptionTR"].ToString();
                x.CaptionDosya = r["CaptionDosya"].ToString();

                cols.Add(r["CaptionDosya"].ToStr(), x);

                if (r["DosyadaZorunlu"].ToStr() != string.Empty)
                    zorunlu.Add(r["CaptionDosya"].ToStr());
            }

            for (int i = 1; i <= 28; i++)
                dtOrd.Columns.Add(string.Format("A{0:00}", i), typeof(int));
            dtOrd.Columns.Add("TotalComputed", typeof(int), "ISNULL(A01,0)+ISNULL(A02,0)+ISNULL(A03,0)+ISNULL(A04,0)+ISNULL(A05,0)+ISNULL(A06,0)+ISNULL(A07,0)+ISNULL(A08,0)+ISNULL(A09,0)+ISNULL(A10,0)+ISNULL(A11,0)+ISNULL(A12,0)+ISNULL(A13,0)+ISNULL(A14,0)+ISNULL(A15,0)+ISNULL(A16,0)+ISNULL(A17,0)+ISNULL(A18,0)+ISNULL(A19,0)+ISNULL(A20,0)+ISNULL(A21,0)+ISNULL(A22,0)+ISNULL(A23,0)+ISNULL(A24,0)+ISNULL(A25,0)+ISNULL(A26,0)+ISNULL(A27,0)+ISNULL(A28,0)");

            dtOrd.Columns.Add("BrandId", typeof(int));
            dtOrd.Columns.Add("SezonId", typeof(int));
            dtOrd.Columns.Add("OrderRef", typeof(string));
            dtOrd.Columns.Add("DagilimId", typeof(int));
            dtOrd.Columns.Add("TalepTipiId", typeof(int));
            dtOrd.Columns.Add("stGenelId", typeof(int));
        }

        List<string> intDates = new List<string>();
        private void SiparisAktar_Load(object sender, EventArgs e)
        {
            switch (CustomerId)
            {
                case 17:
                    //gleSezon.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    break;

                case 96:
                    intDates.Add("Termin");
                    cmbAdetler.EditValue = "AYRI satırlarda";
                    Adet = "Qta residua"; 
                    Beden = "Taglia";
                    break;

                default:
                    cmbAdetler.EditValue = "TEK satırda";
                    break;
            }
        }

        void SiparisAktar_ProcessDone()
        {
            MasterGrid.Init(dtOrd);
            MasterGrid.ShowOnlyNonblankColumns();
            MasterGrid.MakeColumnInvisible("BrandId", "SezonId", "OrderRef", "TalepTipiId", "DagilimId", "stGenelId");
            //MasterGrid.SetIdentity("idx");

            foreach (KeyValuePair<string, cx> ind in cols)
            {
                string colname = ((cx)ind.Value).Col;
                if (gvMaster.DataTable().Columns.Contains(colname))
                {
                    gvMaster.SetCaptions(colname + ":" + ((cx)ind.Value).CaptionTR);
                    gvMaster.Columns[colname].ToolTip = ((cx)ind.Value).CaptionDosya;
                }
            }

            foreach (KeyValuePair<string, string> ind in dag)
            {
                string colname = ind.Value;
                if (gvMaster.DataTable().Columns.Contains(colname))
                {
                    gvMaster.SetCaptions(colname + ":" + (ind.Key));
                    gvMaster.Columns[colname].ToolTip = (ind.Value);
                }
            }

            MasterGrid.AddSummary("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10",
                            "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20",
                            "A21", "A22", "A23", "A24", "A25", "A26", "A27", "A28", "TotalComputed");
            gvMaster.BestFitColumns();

        }


        private void BtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gleMarka.EditValue.ToInt() == 0 ||
                gleTalepTipi.EditValue.ToInt() == 0 ||
                gleSezon.EditValue.ToInt() == 0 ||
                gleDagilim.EditValue.ToInt() == 0)
            {
                ShowErrorMessage("Marka, Sezon, Dağılım ve TalepTipi zorunlu alanlardır, boş bırakılamaz.");
                return;
            }

            gvMaster.EndEditing();

            foreach (DataRow r in gvMaster.DataTable().Rows)
            {
                r["stGenelId"] = 1;
                r["BrandId"] = gleMarka.EditValue.ToInt();
                r["SezonId"] = gleSezon.EditValue.ToInt();

                if (txtOrderRef.EditValue.ToStr() != string.Empty)
                    r["OrderRef"] = txtOrderRef.EditValue.ToStr();

                r["DagilimId"] = gleDagilim.EditValue.ToInt();
                r["TalepTipiId"] = gleTalepTipi.EditValue.ToStr();
            }

            List<string> colList = new List<string>();
            foreach (DataColumn c in gvMaster.DataTable().Columns)
                if (c.ToStr() != "TotalComputed")
                    colList.Add(c.ToStr());

            gvMaster.Update(string.Join(",", colList.ToArray()), "Orders");
            //ExecuteScalar("UpdOrdine", MasterGrid.Serialize(), gleMarka.EditValue.ToInt(), gleSezon.EditValue.ToInt(), gleDagilim.EditValue.ToInt(), txtOrderRef.EditValue.ToStr());

            Notify("Aktarıldı.");
            btnSave.Enabled = false;
        }


        void SiparisAktar_FileDone(DataSet Data, string FileName)
        {
            dtOrd.Clear();
            foreach (DataTable dt in Data.Tables)
            {
                string sheetName = dt.TableName;
                if (sheetName.Contains("Modellen"))
                    continue;

                foreach (string z in zorunlu)
                    if (!dt.Columns.Contains(z))
                    {
                        ShowErrorMessage(sheetName + " sekmesinde " + z + " sutunu yok. Bu sütun zorunlu olarak işaretlendiği için aktarımın yapılabilmesi için eklenmesi gerekiyor.");
                        return;
                    }


                for (int i = 0; i < dt.Columns.Count; i++)
                    if (dt.Rows[0][i].ToStr() != string.Empty)
                        dt.Columns[i].ColumnName = dt.Rows[0][i].ToStr();

                if (cmbAdetler.EditValue.ToStr() == "AYRI satırlarda")
                {
                    int iAdet = 0;
                    if (!dt.Columns.Contains(Adet))
                    {
                        ShowErrorMessage(sheetName + " sekmesinde ADET (" + Adet + ") sutunu yok.");
                        return;
                    }
                    else
                        iAdet = dt.Columns.IndexOf(dt.Columns[Adet]);

                    int iBeden = 0;
                    if (!dt.Columns.Contains(Beden))
                    {
                        ShowErrorMessage(sheetName + " sekmesinde BEDEN (" + Beden + ") sutunu yok.");
                        return;
                    }
                    else
                        iBeden = dt.Columns.IndexOf(dt.Columns[Beden]);

                    DataRow drOrd = dtOrd.NewRow();
                    for (int i = 1; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];

                        bool startnew = false;
                        //if (i > 1)
                        foreach (DataColumn c in dt.Columns)
                            if (c.ToStr() != Adet && c.ToStr() != Beden)
                                if (!object.Equals(dt.Rows[i][c], dt.Rows[i - 1][c]))
                                {
                                    startnew = true;
                                    break;
                                }

                        if (startnew)   //yeni bir pos'a geçtiysen
                        {
                            //if (drOrd["Model"].ToStr() != string.Empty)
                            if (i > 1)
                                dtOrd.Rows.Add(drOrd);  //eskisini yaz

                            drOrd = dtOrd.NewRow(); //yeni başlat
                            drOrd["DosyaAdi"] = Path.GetFileName(FileName) + "; " + sheetName;
                            foreach (KeyValuePair<string, cx> ind in cols)
                                if (dt.Columns.Contains(ind.Key))
                                {
                                    if (intDates.Contains(((cx)ind.Value).Col))
                                        drOrd[((cx)ind.Value).Col] = DateTime.FromOADate((double)dr[ind.Key].ToInt());
                                    else
                                        drOrd[((cx)ind.Value).Col] = dr[ind.Key];
                                }
                        }

                        if (dag.ContainsKey(dr[Beden].ToStr()))
                            if (dr[Adet].ToInt() > 0)
                                drOrd[dag[dr[Beden].ToStr()]] = dr[Adet].ToInt();   //bedeni oku ve yaz


                    }
                    dtOrd.Rows.Add(drOrd);  //eskisini yaz

                }
                else
                {
                    int yildiz = 0;
                    if (!dt.Columns.Contains("*"))
                    {
                        ShowErrorMessage(sheetName + " sekmesinde * sutunu yok. Adetlerden hemen önceki sütunun başlığı * olmalı.");
                        return;
                    }
                    else
                        yildiz = dt.Columns.IndexOf(dt.Columns["*"]);

                    for (int i = 1; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];

                        DataRow drOrd = dtOrd.NewRow();
                        drOrd["DosyaAdi"] = Path.GetFileName(FileName) + "; " + sheetName;
                        foreach (KeyValuePair<string, cx> ind in cols)
                            if (dt.Columns.Contains(ind.Key))
                                drOrd[((cx)ind.Value).Col] = dr[ind.Key];

                        for (int j = yildiz + 1; j < dt.Columns.Count; j++)
                            if (dag.ContainsKey(dt.Columns[j].ToStr()))
                                if (dr[j].ToInt() > 0)
                                    drOrd[dag[dt.Columns[j].ToStr()]] = dr[j].ToInt();

                        if (drOrd["Model"].ToStr() != string.Empty)
                            dtOrd.Rows.Add(drOrd);
                    }
                }
            }
        }

    }

    public class cx
    {
        public string Col;
        public string CaptionTR;
        public string CaptionDosya;
    }
}
